package demo;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：黄淼淳
 * @date ：2021/12/18 20:02
 * @description：测试volatile的作用
 */
public class VolatileDemo {
    public static void main(String[] args) throws InterruptedException {
        Person person = new Person();
        CountDownLatch count = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                    for (int j = 0; j < 1000; j++) {
                        person.add();
                    }
                count.countDown();
            }, String.valueOf(i + 1)).start();
        }
        count.await();
        System.out.println(person.num);
    }
}

class Person {
   /* //得到的值小于1000,即线程不安全
    volatile int num = 0;

    void add() {
        num++;
    }*/

   /* //线程安全
    AtomicInteger num = new AtomicInteger(0);

    void add() {
        num.getAndIncrement();
    }*/

    //加锁
    int num = 0;
    synchronized void add(){
        num++;
    }

   /* Lock lock = new ReentrantLock();
    int num = 0;
    void add (){
        lock.lock();
        try{
            num++;
        } finally {
            lock.unlock();
        }
    }*/


}
